package com.buyi.easyhome.worker

import android.content.Context
import android.speech.tts.TextToSpeech
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.buyi.easyhome.util.AudioPlayer
import com.buyi.easyhome.util.BatteryAlarmType
import java.util.Locale

class PlayTextWorker(appContext: Context, workerParams: WorkerParameters) :
    Worker(appContext, workerParams) {

    private val TAG = "PlayTextIntentService"

    override fun doWork(): Result {
        Log.d(TAG, "IntentService is handling intent msg")

        val playType = inputData.getString("playType") ?: BatteryAlarmType.TTS.name
        if (playType == BatteryAlarmType.AUDIO.name) {
            val resids = inputData.getIntArray("resids") ?: return Result.failure()
            val ap = AudioPlayer()
            for (resid in resids) {
                ap.addAudioFile(applicationContext.resources.openRawResourceFd(resid))
            }
            ap.play()
            return Result.success()
        }

        val message = inputData.getString("textToSpeechText") ?: return Result.failure()

        var tts: TextToSpeech? = null
        var initStatus = 0
        tts = TextToSpeech(applicationContext) { status ->
            if (status == TextToSpeech.SUCCESS) {
                initStatus = 1
                Log.d(TAG, "TTSHelper: tts init success!")
                tts?.language = Locale.getDefault()
                tts?.setSpeechRate(1.2f)
            } else {
                initStatus = 2
                Log.e(TAG, "TTSHelper: tts init failed!")
            }
        }

        while (initStatus == 0) {
            Thread.sleep(1000)
        }

        if (initStatus == 2) {
            Log.e(TAG, "TTS init failed")
            return Result.failure()
        }

        tts.speak(message, TextToSpeech.QUEUE_FLUSH, null, "tts")
        Log.d(TAG, "play success")

        return Result.success()
    }
}